from http.server import HTTPServer, SimpleHTTPRequestHandler
import os, sys, ssl, webbrowser, socket, argparse

# run as windows exe file, set to True
# run as python file, set to False
# 如果打包成exe, 需要将该项设置为True
# 如果作为python程序, 则设置为False
IS_EXE = True

def main():
  script_name = os.path.basename(sys.argv[0])
  print("")
  print("run [ %s -h ] for more help" % script_name)

  parser = argparse.ArgumentParser()

  parser.add_argument("--local_ip", help="set host as local ip address", action="store_true")
  parser.add_argument("--host", default="localhost")
  parser.add_argument("--port", type=int, default=4443)
  parser.add_argument("--https", help="base on https", action="store_true")

  args = parser.parse_args()

  if IS_EXE:
    CERT_PATH    = os.path.join(os.path.dirname(sys.executable), "server.pem")
  else:
    CERT_PATH    = os.path.join(os.path.dirname(sys.argv[0]), "server.pem")

  PROTOCOL       = "https" if args.https else "http"
  HOST           = socket.gethostbyname(socket.gethostname()) if args.local_ip else args.host
  PORT           = args.port
  SERVER_ADDRESS = (HOST, PORT)

  URL = "%s://%s:%s/" % (PROTOCOL, HOST, PORT)

  httpd = HTTPServer(SERVER_ADDRESS, SimpleHTTPRequestHandler)

  if args.https:
    try:
      httpd.socket = ssl.wrap_socket (httpd.socket, certfile=CERT_PATH, server_side=True)
    except FileNotFoundError:
      print("[error] cert file not found: %s" % CERT_PATH)
      return False

  print("")
  print("server running on %s" % URL)
  print("")
  webbrowser.open(URL)

  httpd.serve_forever()


if __name__ == "__main__":
  try:
    os.system("@echo off")
    main()
  except BaseException as e:
    print(e)
    os.system("pause")
